<template>
  <div class="document-editor-container">
    <!-- 编辑器头部 -->
    <div class="editor-header">
      <div class="header-left">
        <el-button icon="ArrowLeft" @click="goBack">返回</el-button>
        <div class="document-info">
          <el-input
            v-model="document.title"
            placeholder="请输入文档标题"
            class="title-input"
            size="large"
          />
          <div class="document-meta">
            <span class="save-status">{{ saveStatus }}</span>
            <span class="last-save-time" v-if="lastSaveTime">
              最后保存：{{ formatTime(lastSaveTime) }}
            </span>
          </div>
        </div>
      </div>
      
      <div class="header-right">
        <el-button-group>
          <el-button icon="View" @click="togglePreview">
            {{ showPreview ? '编辑' : '预览' }}
          </el-button>
          <el-button icon="Share" @click="shareDocument">分享</el-button>
          <el-button icon="Download" @click="exportDocument">导出</el-button>
        </el-button-group>
        <el-button type="primary" @click="saveDocument" :loading="saving">
          保存
        </el-button>
      </div>
    </div>

    <!-- 编辑器工具栏 -->
    <div class="editor-toolbar" v-if="!showPreview">
      <el-button-group size="small">
        <el-button icon="Bold" @click="insertFormat('**', '**')">粗体</el-button>
        <el-button icon="Italic" @click="insertFormat('*', '*')">斜体</el-button>
        <el-button icon="Underline" @click="insertFormat('<u>', '</u>')">下划线</el-button>
      </el-button-group>
      
      <el-divider direction="vertical" />
      
      <el-button-group size="small">
        <el-button @click="insertHeading(1)">H1</el-button>
        <el-button @click="insertHeading(2)">H2</el-button>
        <el-button @click="insertHeading(3)">H3</el-button>
      </el-button-group>
      
      <el-divider direction="vertical" />
      
      <el-button-group size="small">
        <el-button icon="List" @click="insertList('- ')">列表</el-button>
        <el-button icon="Numbered" @click="insertList('1. ')">编号</el-button>
        <el-button icon="Link" @click="showLinkDialog = true">链接</el-button>
        <el-button icon="Picture" @click="showImageDialog = true">图片</el-button>
      </el-button-group>
      
      <el-divider direction="vertical" />
      
      <el-button-group size="small">
        <el-button icon="Code" @click="insertCode">代码</el-button>
        <el-button icon="Table" @click="insertTable">表格</el-button>
        <el-button icon="Quote" @click="insertQuote">引用</el-button>
      </el-button-group>
    </div>

    <!-- 编辑器主体 -->
    <div class="editor-body">
      <div class="editor-content" v-if="!showPreview">
        <el-input
          ref="editorRef"
          v-model="document.content"
          type="textarea"
          placeholder="开始编写您的文档..."
          class="content-editor"
          @input="handleContentChange"
          @keydown="handleKeydown"
        />
      </div>
      
      <div class="preview-content" v-else>
        <div class="markdown-body" v-html="renderedContent"></div>
      </div>
    </div>

    <!-- 侧边栏 -->
    <div class="editor-sidebar">
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="大纲" name="outline">
          <div class="outline-content">
            <div 
              v-for="heading in outlineData"
              :key="heading.id"
              :class="['outline-item', `level-${heading.level}`]"
              @click="scrollToHeading(heading.id)"
            >
              {{ heading.text }}
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="模板" name="templates">
          <div class="templates-content">
            <div 
              v-for="template in templates"
              :key="template.id"
              class="template-item"
              @click="useTemplate(template)"
            >
              <div class="template-name">{{ template.name }}</div>
              <div class="template-desc">{{ template.description }}</div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="历史" name="history">
          <div class="history-content">
            <div 
              v-for="version in versions"
              :key="version.id"
              class="version-item"
              @click="loadVersion(version)"
            >
              <div class="version-time">{{ formatTime(version.createTime) }}</div>
              <div class="version-desc">{{ version.description }}</div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 链接对话框 -->
    <el-dialog v-model="showLinkDialog" title="插入链接" width="400px">
      <el-form :model="linkForm" label-width="60px">
        <el-form-item label="文本">
          <el-input v-model="linkForm.text" placeholder="链接文本" />
        </el-form-item>
        <el-form-item label="链接">
          <el-input v-model="linkForm.url" placeholder="https://" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showLinkDialog = false">取消</el-button>
        <el-button type="primary" @click="insertLink">确定</el-button>
      </template>
    </el-dialog>

    <!-- 图片对话框 -->
    <el-dialog v-model="showImageDialog" title="插入图片" width="400px">
      <el-form :model="imageForm" label-width="60px">
        <el-form-item label="描述">
          <el-input v-model="imageForm.alt" placeholder="图片描述" />
        </el-form-item>
        <el-form-item label="链接">
          <el-input v-model="imageForm.url" placeholder="图片链接" />
        </el-form-item>
        <el-form-item label="上传">
          <el-upload
            class="upload-demo"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleImageUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showImageDialog = false">取消</el-button>
        <el-button type="primary" @click="insertImage">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getDocumentDetail,
  createDocument,
  updateDocument,
  getDocumentTemplates,
  getDocumentVersions
} from '@/api/document'
import { formatTime } from '@/utils'

const route = useRoute()
const router = useRouter()

// 响应式数据
const document = reactive({
  id: null,
  title: '',
  content: '',
  categoryId: null,
  tags: []
})

const showPreview = ref(false)
const activeTab = ref('outline')
const saving = ref(false)
const saveStatus = ref('已保存')
const lastSaveTime = ref(null)
const templates = ref([])
const versions = ref([])
const outlineData = ref([])

// 对话框状态
const showLinkDialog = ref(false)
const showImageDialog = ref(false)

// 表单数据
const linkForm = reactive({
  text: '',
  url: ''
})

const imageForm = reactive({
  alt: '',
  url: ''
})

// 编辑器引用
const editorRef = ref()

// 计算属性
const renderedContent = computed(() => {
  // 这里应该使用 markdown 解析器，简化处理
  return document.content.replace(/\n/g, '<br>')
})

// 页面加载
onMounted(async () => {
  if (route.params.id && route.params.id !== 'create') {
    await loadDocument()
  }
  await loadTemplates()
  
  // 自动保存
  startAutoSave()
})

// 页面卸载
onUnmounted(() => {
  stopAutoSave()
})

// 监听内容变化
watch(() => document.content, () => {
  updateOutline()
  saveStatus.value = '未保存'
})

// 加载文档
const loadDocument = async () => {
  try {
    const response = await getDocumentDetail(route.params.id)
    if (response.code === 200) {
      Object.assign(document, response.data)
      await loadVersions()
    }
  } catch (error) {
    console.error('加载文档失败:', error)
    ElMessage.error('加载文档失败')
  }
}

// 加载模板
const loadTemplates = async () => {
  try {
    const response = await getDocumentTemplates()
    if (response.code === 200) {
      templates.value = response.data || []
    }
  } catch (error) {
    console.error('加载模板失败:', error)
  }
}

// 加载版本历史
const loadVersions = async () => {
  try {
    const response = await getDocumentVersions(document.id)
    if (response.code === 200) {
      versions.value = response.data || []
    }
  } catch (error) {
    console.error('加载版本历史失败:', error)
  }
}

// 保存文档
const saveDocument = async () => {
  if (!document.title.trim()) {
    ElMessage.warning('请输入文档标题')
    return
  }
  
  saving.value = true
  try {
    if (document.id) {
      await updateDocument(document.id, document)
    } else {
      const response = await createDocument(document)
      if (response.code === 200) {
        document.id = response.data.id
        router.replace(`/document/${document.id}/edit`)
      }
    }
    
    saveStatus.value = '已保存'
    lastSaveTime.value = new Date()
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 自动保存
let autoSaveTimer = null

const startAutoSave = () => {
  autoSaveTimer = setInterval(() => {
    if (saveStatus.value === '未保存' && document.title.trim()) {
      saveDocument()
    }
  }, 30000) // 30秒自动保存
}

const stopAutoSave = () => {
  if (autoSaveTimer) {
    clearInterval(autoSaveTimer)
    autoSaveTimer = null
  }
}

// 编辑器功能
const insertFormat = (before, after) => {
  const textarea = editorRef.value?.textarea
  if (!textarea) return
  
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const selectedText = document.content.substring(start, end)
  const replacement = before + selectedText + after
  
  document.content = document.content.substring(0, start) + replacement + document.content.substring(end)
  
  // 设置光标位置
  setTimeout(() => {
    textarea.focus()
    textarea.setSelectionRange(start + before.length, start + before.length + selectedText.length)
  })
}

const insertHeading = (level) => {
  const prefix = '#'.repeat(level) + ' '
  insertAtCursor(prefix)
}

const insertList = (prefix) => {
  insertAtCursor('\n' + prefix)
}

const insertCode = () => {
  insertFormat('```\n', '\n```')
}

const insertTable = () => {
  const table = '\n| 列1 | 列2 | 列3 |\n|-----|-----|-----|\n| 内容 | 内容 | 内容 |\n'
  insertAtCursor(table)
}

const insertQuote = () => {
  insertAtCursor('\n> ')
}

const insertAtCursor = (text) => {
  const textarea = editorRef.value?.textarea
  if (!textarea) return
  
  const start = textarea.selectionStart
  document.content = document.content.substring(0, start) + text + document.content.substring(start)
  
  setTimeout(() => {
    textarea.focus()
    textarea.setSelectionRange(start + text.length, start + text.length)
  })
}

// 插入链接
const insertLink = () => {
  if (!linkForm.text || !linkForm.url) {
    ElMessage.warning('请填写链接文本和地址')
    return
  }
  
  const linkText = `[${linkForm.text}](${linkForm.url})`
  insertAtCursor(linkText)
  
  linkForm.text = ''
  linkForm.url = ''
  showLinkDialog.value = false
}

// 插入图片
const insertImage = () => {
  if (!imageForm.url) {
    ElMessage.warning('请填写图片地址')
    return
  }
  
  const imageText = `![${imageForm.alt}](${imageForm.url})`
  insertAtCursor(imageText)
  
  imageForm.alt = ''
  imageForm.url = ''
  showImageDialog.value = false
}

// 图片上传成功
const handleImageUpload = (response) => {
  if (response.code === 200) {
    imageForm.url = response.data.url
    ElMessage.success('图片上传成功')
  }
}

// 切换预览
const togglePreview = () => {
  showPreview.value = !showPreview.value
}

// 更新大纲
const updateOutline = () => {
  const headings = []
  const lines = document.content.split('\n')
  
  lines.forEach((line, index) => {
    const match = line.match(/^(#{1,6})\s+(.+)/)
    if (match) {
      headings.push({
        id: `heading-${index}`,
        level: match[1].length,
        text: match[2],
        line: index
      })
    }
  })
  
  outlineData.value = headings
}

// 滚动到标题
const scrollToHeading = (headingId) => {
  // 实现滚动到指定标题的逻辑
}

// 使用模板
const useTemplate = (template) => {
  document.content = template.content
  ElMessage.success('模板已应用')
}

// 加载版本
const loadVersion = (version) => {
  document.content = version.content
  ElMessage.success('版本已加载')
}

// 分享文档
const shareDocument = () => {
  if (!document.id) {
    ElMessage.warning('请先保存文档')
    return
  }
  
  const url = `${window.location.origin}/document/${document.id}`
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('分享链接已复制到剪贴板')
  })
}

// 导出文档
const exportDocument = () => {
  if (!document.title.trim()) {
    ElMessage.warning('请先输入文档标题')
    return
  }
  
  const blob = new Blob([document.content], { type: 'text/markdown' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${document.title}.md`
  a.click()
  URL.revokeObjectURL(url)
}

// 返回
const goBack = () => {
  if (saveStatus.value === '未保存') {
    ElMessage.confirm('文档尚未保存，确定要离开吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.back()
    }).catch(() => {})
  } else {
    router.back()
  }
}

// 键盘快捷键
const handleKeydown = (event) => {
  if (event.ctrlKey || event.metaKey) {
    switch (event.key) {
      case 's':
        event.preventDefault()
        saveDocument()
        break
      case 'b':
        event.preventDefault()
        insertFormat('**', '**')
        break
      case 'i':
        event.preventDefault()
        insertFormat('*', '*')
        break
    }
  }
}

// 内容变化处理
const handleContentChange = () => {
  updateOutline()
}
</script>

<style lang="scss" scoped>
.document-editor-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .document-info {
      .title-input {
        width: 300px;
        
        :deep(.el-input__wrapper) {
          border: none;
          box-shadow: none;
          font-size: 18px;
          font-weight: 600;
        }
      }
      
      .document-meta {
        display: flex;
        gap: 16px;
        font-size: 12px;
        color: #909399;
        margin-top: 4px;
      }
    }
  }
  
  .header-right {
    display: flex;
    gap: 12px;
  }
}

.editor-toolbar {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
}

.editor-body {
  flex: 1;
  display: flex;
  overflow: hidden;
  
  .editor-content {
    flex: 1;
    padding: 20px;
    
    .content-editor {
      height: 100%;
      
      :deep(.el-textarea__inner) {
        height: 100%;
        border: none;
        resize: none;
        font-family: 'Monaco', 'Consolas', monospace;
        font-size: 14px;
        line-height: 1.6;
      }
    }
  }
  
  .preview-content {
    flex: 1;
    padding: 20px;
    background: white;
    overflow-y: auto;
    
    .markdown-body {
      max-width: 800px;
      margin: 0 auto;
      line-height: 1.6;
      color: #333;
    }
  }
}

.editor-sidebar {
  width: 300px;
  background: white;
  border-left: 1px solid #e4e7ed;
  
  .outline-content {
    padding: 16px;
    
    .outline-item {
      padding: 4px 0;
      cursor: pointer;
      color: #606266;
      
      &:hover {
        color: #409eff;
      }
      
      &.level-1 { padding-left: 0; font-weight: 600; }
      &.level-2 { padding-left: 16px; }
      &.level-3 { padding-left: 32px; }
      &.level-4 { padding-left: 48px; }
      &.level-5 { padding-left: 64px; }
      &.level-6 { padding-left: 80px; }
    }
  }
  
  .templates-content,
  .history-content {
    padding: 16px;
    
    .template-item,
    .version-item {
      padding: 12px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      margin-bottom: 8px;
      cursor: pointer;
      
      &:hover {
        border-color: #409eff;
      }
      
      .template-name,
      .version-time {
        font-weight: 500;
        color: #303133;
      }
      
      .template-desc,
      .version-desc {
        font-size: 12px;
        color: #909399;
        margin-top: 4px;
      }
    }
  }
}

@media (max-width: 768px) {
  .editor-header {
    flex-direction: column;
    gap: 12px;
    
    .header-left {
      width: 100%;
      justify-content: space-between;
    }
  }
  
  .editor-toolbar {
    flex-wrap: wrap;
  }
  
  .editor-body {
    flex-direction: column;
    
    .editor-sidebar {
      width: 100%;
      height: 200px;
      border-left: none;
      border-top: 1px solid #e4e7ed;
    }
  }
}
</style>
